<template>
  <button
    class="float-button"
    :style="{ right: buttonRight, bottom: buttonBottom}"
    style="box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2);"
    @click="onClick">
    <!-- 按钮内容 -->
    <slot>+</slot>
  </button>
  <el-drawer v-model="isShow" title="I am the title" :with-header="false" style="max-width: 370px; ">

    <el-row :gutter="10">
    <el-col :span="16">
        <el-select
          v-model="value"
          placeholder="Select"
          style="width: 90%;"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
    </el-col>

    <el-col :span="8">
      <el-button text @click="openExit">设置</el-button>
    </el-col>

  </el-row>

  <el-dialog v-model="dialogForm" title="设置" width="50%" style="margin-top: 30px;">
    <el-form :model="form">
      <el-form-item label="名称" :default="form.name" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="仓库地址" :label-width="formLabelWidth">
        <el-input v-model="form.url" autocomplete="off" />
      </el-form-item>
      <el-form-item label="本地路径" :label-width="formLabelWidth">
        <el-button  style="width: 100%;" @click="choiceDir">
          <div v-if="form.path == ''">
            选择
          </div>
          <div v-if="form.path != ''">
            {{form.path}}
          </div>
        </el-button>
      </el-form-item>
      <el-form-item label="用户名" :label-width="formLabelWidth">
        <el-input v-model="form.userName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="邮箱" :label-width="formLabelWidth">
        <el-input v-model="form.email" autocomplete="off" />
      </el-form-item>
      <el-form-item label="登录名" :label-width="formLabelWidth">
        <el-input v-model="form.login_name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" :label-width="formLabelWidth">
        <el-input type="password" v-model="form.password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="描述" :label-width="formLabelWidth">
        <el-input v-model="form.desc" autocomplete="off" />
      </el-form-item>

      <el-button text @click="pull">拉取全部</el-button>
      <el-button text @click="pushAll">推送全部</el-button>

    </el-form>


    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogForm = false">取消</el-button>
        <el-button type="primary" @click="exitConfig">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>




    <el-tree v-show="isCollapse"
      style="max-width: 600px; margin-left: -20px;"
      :allow-drop="local_allowDrop"
      :allow-drag="local_allowDrag"
      :data="treeData"
      draggable

      node-key="id"
   
      @node-drag-start="local_handleDragStart"
      @node-drag-enter="local_handleDragEnter"
      @node-drag-leave="local_handleDragLeave"
      @node-drag-over="local_handleDragOver"
      @node-drag-end="local_handleDragEnd"
      @node-drop="local_handleDrop"
      @node-click="local_handleNodeClick"
      :expand-on-click-node="false"
      :render-content="local_renderContent"
      icon="Files"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>
            <a style="margin-right: 20px" @click="local_upload(node, data)"> 上传 </a>
            <a style="margin-right: 10px" @click="local_remove(node, data)"> 移除 </a>
          </span>
        </span>
      </template>
    </el-tree>

</el-drawer>

  </template>
   
<script lang="ts" setup>
import { ref, watch, onMounted, reactive } from 'vue';
import { readTextFile, writeTextFile, create, exists, BaseDirectory } from '@tauri-apps/plugin-fs';
import { open, ask } from "@tauri-apps/plugin-dialog"
import { invoke } from "@tauri-apps/api/core";
const configName = "config.json";
//弹出框
const dialogForm = ref(false)
const formLabelWidth = '20%'
const form = reactive({
  name: '',
  url: '',
  path: '',
  userName: '',
  email: '',
  login_name: '',
  password: '',
  desc: '',
})


//下拉
const value = ref('无')
const options: any[] = [
  // {
  //   value: '无',
  //   label: '无',
  // }
]

function openExit() {
  dialogForm.value = true
  console.log(JSON.stringify(form))
}

async function choiceDir() {
  const path : string|null = await open({
    multiple: false,
    directory: true,
  })
  if (path) {
    form.path = path;
  }
}


async function exitConfig() {
  dialogForm.value = false; 

  if (!form.path || form.path.length == 0) {
    alert("本地地址没有填写!");
  } else 
  if (form.url && form.url.length > 0) {
    if (!form.userName || form.userName.length == 0) {
      alert("用户名没有填写!");
    } else 
    if (!form.email || form.email.length == 0) {
      alert("邮箱没有填写!");
    } else 
    if (!form.login_name || form.login_name.length == 0) {
      alert("登录名没有填写!");
    } else 
    if (!form.password || form.password.length == 0) {
      alert("密码没有填写!");
    }
  }
  console.log(JSON.stringify(form))
  await saveCacheFile(configName, JSON.stringify(form));

  treeData.value = await invoke("get_list_file", {path: form.path + "\\" + form.name});

  if (form.url && form.path) {
      await invoke("init_repository", {url: form.url, path: form.path + "\\" + form.name});
  }

}

interface Tree{
  label: string,
  children: Array<Tree>,
  fileId: number,
  path: string
}

onMounted(async () => { 
      //判断默认文件是否存在
      let data = await getCacheFile(configName);
      console.log(data)
      if (data) {
          // 转成json字符串并格式化
          let json = JSON.parse(data);
          json.name
          form.name = json.name;
          form.url = json.url;
          form.path = json.path;
          form.userName = json.userName;
          form.email = json.email;
          form.login_name = json.login_name;
          form.password = json.password;
          form.desc = json.desc;
          if (form.url) {
            await invoke("pull", {url: form.url, path: form.path + "\\" + form.name});
          }
      }
      options.push({
        value: form.name,
        label: form.name,
      });
      value.value = form.name;



      treeData.value = await invoke("get_list_file", {path: form.path + "\\" + form.name});

      //console.log(JSON.stringify(treeData.value))

     



      emit("tree", treeData.value);

      //读取地址文件
      watch(props, async () => {
          if (props.addPath) {
            console.log("add")
            for (let t = 0; t <  treeData.value.length; t++) {
              if (treeData.value[t].path === props.addPath) {
                return;
              }
            }
            let tt : Tree = {
              label: getFileName(props.addPath),
              children: [],
              fileId: 0,
              path: props.addPath
            }
            treeData.value.push(tt)
            if (form.url) {
              await invoke("push", {url: form.url, path: form.path + "\\" + form.name + "\\", filePath: props.addPath, username: form.userName, email: form.email, loginName: form.login_name, password: form.password});
            }

            //await writeTextFile(cache, JSON.stringify(treeData.value), { baseDir: BaseDirectory.AppData })
          }

          if (props.delPath) {
            console.log("del")
            for (let t = 0; t <  treeData.value.length; t++) {
              if (treeData.value[t].path === props.delPath) {
                treeData.value.splice(t, 1);
                break
              }
            }
            //await writeTextFile(cache, JSON.stringify(treeData.value), { baseDir: BaseDirectory.AppData })
          }
      })
})



async function pull () {
  if (form.url) {
    await invoke("pull", {url: form.url, path: form.path + "\\" + form.name});
    treeData.value = await invoke("get_list_file", {path: form.path + "\\" + form.name});
  }
}


async function pushAll() {
  if (form.url) {
    await invoke("push_all", {url: form.url, path: form.path + "\\" + form.name + "\\", username: form.userName, email: form.email, loginName: form.login_name, password: form.password});
    treeData.value = await invoke("get_list_file", {path: form.path + "\\" + form.name});
  }

}


const getCacheFile = async (cacheFileName: string | URL) : Promise<string> => {
  console.log("获取文件")
      //判断默认文件是否存在
    const exit = await exists(cacheFileName, { baseDir: BaseDirectory.AppData });
    if (!exit) {
    await create(cacheFileName, { baseDir: BaseDirectory.AppData })
    }
    let data = await readTextFile(cacheFileName, { baseDir: BaseDirectory.AppData })
    if (data) {
        // 转成json字符串并格式化
        return data;
    }
    return "";
}


const saveCacheFile = async (cacheFileName: string | URL, data: string) => {
  await writeTextFile(cacheFileName, data, { baseDir: BaseDirectory.AppData }) 
}

//////////////////////////

const isCollapse = ref(true)


const local_upload = async (node: Node, data: Tree) => {
  let rest:string = await invoke("read_file", {path: data.path});
  console.log("********" + rest);
  if (rest.indexOf("#@#error#@#_") > -1) {
    alert(rest.replace("#@#error#@#_", ""));
    rest = "";
  }
  if (rest) {
    let fileId:number = await invoke("save_file", {content: rest, path: data.path});
    data.fileId = fileId;
    const parent = node.parent
    const children: Tree[] = parent.data.children || parent.data
    const index = children.findIndex((d) => d.label === data.label)
    treeData.value[index].fileId = fileId;
    //await writeTextFile(cache, JSON.stringify(treeData.value), { baseDir: BaseDirectory.AppData })
    if (form.url) {
      await invoke("push", {url: form.url, path: form.path + "\\" + form.name + "\\", filePath: data.path, username: form.userName, email: form.email, loginName: form.login_name, password: form.password});
    }
  }
}




const local_remove = async (node: Node, data: Tree) => {
  const parent = node.parent
  const children: Tree[] = parent.data.children || parent.data
  const index = children.findIndex((d) => d.label === data.label)
  const answer = await ask("是否清楚当前文件？", {
    title: "提示",
    kind: "warning",
    okLabel:"清理",
    cancelLabel:"取消"
  });
  if (answer) {
    children.splice(index, 1)
    treeData.value.splice(index, 1);
    await invoke("del_file", {path: data.path});
    //await writeTextFile(cache, JSON.stringify(treeData.value), { baseDir: BaseDirectory.AppData })
    //push_del_file
    if (form.url) {
      await invoke("push_del_file", {url: form.url, path: form.path + "\\" + form.name + "\\", filePath: data.path, username: form.userName, email: form.email, loginName: form.login_name, password: form.password});
    }

  } else {
    
  }
}


const emit = defineEmits(['filePath', "tree", 'fileId'])



const props = defineProps({
  userId: String,
  addPath: String,
  delPath: String,
})
console.log(props.userId)

const treeData = ref<Array<Tree>>([]);


const buttonRight = ref('30px'); // 可以根据需要调整位置
const buttonBottom = ref('30px');

const isShow = ref(false);

function onClick() {
  isShow.value = true;
}
function getFileName(filePath: string) : string {
  let split = filePath.split("\\");
  let fileName = split[split.length-1];
  return fileName;
}

//树
import type Node from 'element-plus/es/components/tree/src/model/node'
import type { DragEvents } from 'element-plus/es/components/tree/src/model/useDragNode'
import type {
  AllowDropType,
  NodeDropType,
} from 'element-plus/es/components/tree/src/tree.type'

//本地
const local_handleDragStart = (node: Node, _: DragEvents) => {
  console.log('drag start', node)
}
const local_handleDragEnter = (
  dropNode: Node,
) => {
  console.log('tree drag enter:', dropNode.label)
}
const local_handleDragLeave = (
  dropNode: Node,
) => {
  console.log('tree drag leave:', dropNode.label)
}
const local_handleDragOver = (_1: Node, dropNode: Node, _: DragEvents) => {
  console.log('tree drag over:', dropNode.label)
}
const local_handleDragEnd = (
  dropNode: Node,
  dropType: NodeDropType,
) => {
  console.log('tree drag end:', dropNode && dropNode.label, dropType)
}
const local_handleDrop = (
  dropNode: Node,
  dropType: NodeDropType,
) => {
  console.log('tree drop:', dropNode.label, dropType)
}

const local_handleNodeClick = (data: Tree) => {
  console.log(data.path)
  emit('filePath', data.path);
  emit('fileId', null);
}

const local_allowDrop = (_: Node, dropNode: Node, type: AllowDropType) => {
  if (dropNode.data.label === 'Level two 3-1') {
    return type !== 'inner'
  } else {
    return true
  }
}
const local_allowDrag = (draggingNode: Node) => {
  return !draggingNode.data.label.includes('Level three 3-1-1')
}
const local_renderContent = (
  h:any,
  {
    node,
    data,
  }: {
    node: Node
    data: Tree
    store: Node['store']
  }
) => {
  return h(
    'span',
    {
      class: 'custom-tree-node',
    },
    h('span', null, node.label),
    h(
      'span',
      null,
      h(
        'a',
        {
          style: 'margin-left: 3px;',
          onClick: () => local_upload(node, data),
        },
        '上传 '
      ),
      h(
        'a',
        {
          style: 'margin-left: 9px;',
          onClick: () => local_remove(node, data),
        },
        '移除'
      )
    )
  )
}




</script>
   
<style scoped>
.float-button {
  position: fixed;
  z-index: 1000; /* 确保按钮在最上层 */
  cursor: pointer;
  /* 其他样式按需添加 */
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}



</style>